<template>
  <el-dialog title="导入" width="500px" :visible.sync="visible" :close-on-click-modal="false" :before-close="beforeClose">
    <el-form :model="form" label-width="80px" :rules="formRule" ref="form">
      <el-form-item label="月份" prop="acctMonth">
        <el-date-picker value-format="yyyyMM" v-model="form.acctMonth" type="month" placeholder="请选择月份" :clearable="false"></el-date-picker>
      </el-form-item>

      <el-form-item label="上传文件" prop="file" :rules="{ validator: checkFile, trigger: 'blur', required: true}">
        <el-upload ref="upload" action="/api/oneAdjustment/import" accept=".xlsx, .xls" :limit="1" :data="form" :on-success="handleFileSuccess" :on-progress="progress" :auto-upload="false"
          :file-list="fileList" :on-change="handleChange" :on-remove="handleRemove">
          <el-button size="small" type="orange">导入</el-button>
        </el-upload>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitFileForm">确 定</el-button>
      <el-button @click="beforeClose">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getCookie } from "@/common/js/cookie";
export default {
  data() {
    var checkFile = (rule, value, callback) => {
      if (this.fileList.length == 0) {
        callback(new Error("请上传文件"));
      } else {
        callback();
      }
    };
    return {
      visible: false,
      form: {
        acctMonth: this.dayjs().format("YYYYMM"),
        token: null,
      },
      fileList: [],
      loading: null,
      formRule: {
        acctMonth: { required: true, message: "请选择月份", trigger: "blur" },
      },
      checkFile,
    };
  },
  created() {
    this.form.token = getCookie("token");
  },
  methods: {
    init() {
      this.visible = true;
    },
    // 提交上传文件
    async submitFileForm() {
      await this.$refs.form.validate();
      this.$refs.upload.submit();
    },
    // 文件上传成功处理
    handleFileSuccess(res, file, fileList) {
      console.log(res);
      if (res.code == 0) {
        this.$message.success("导入成功");
        this.visible = false;
        this.$emit("refresh");
      } else {
        this.$message.error(res.message);
        this.$refs.upload.clearFiles();
      }
      this.loading.close();
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(0);
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.fileList = fileList.slice(0);
    },
    errorUpload(err, file, fileList) {
      this.loading.close();
    },
    progress(event, file, fileList) {
      this.loading = this.$loading({
        lock: true,
        text: "正在导入",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    beforeClose() {
      this.visible = false;
      this.fileList.splice(0);
      // this.$refs.upload.clearFiles();
    },
  },
};
</script>